package com.sdhs.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdhs.common.core.domain.BaseEntity;
import com.sdhs.common.core.domain.entity.SysUser;
import com.sdhs.common.core.page.PageQuery;
import com.sdhs.common.core.page.TableDataInfo;
import com.sdhs.common.utils.ConvertUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.system.service.ISysDeptService;
import com.sdhs.system.service.ISysUserService;
import com.sdhs.workflow.common.enums.ApproveCodeConfigEnum;
import com.sdhs.workflow.domain.WfApproveUserConfig;
import com.sdhs.workflow.domain.bo.WfApproveUserConfigBo;
import com.sdhs.workflow.domain.vo.WfApproveUserConfigVo;
import com.sdhs.workflow.mapper.WfApproveUserConfigMapper;
import com.sdhs.workflow.service.IWfApproveUserConfigService;
import com.sdhs.workflow.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程审批人配置Service业务层处理
 *
 * @author may
 * @date 2023-07-21
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class WfApproveUserConfigServiceImpl implements IWfApproveUserConfigService {

    private final WfApproveUserConfigMapper baseMapper;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询流程审批人配置
     */
    @Override
    public WfApproveUserConfigVo queryById(Long id) {
        WfApproveUserConfigVo wfApproveUserConfigVo = baseMapper.selectVoById(id);

        String approveNodeUserIds = wfApproveUserConfigVo.getApproveNodeUserIds();
        if (StringUtils.isEmpty(approveNodeUserIds)) {
            return wfApproveUserConfigVo;
        }

        // 获取列表中所有的审批人id
        String[] split = approveNodeUserIds.split(",");
        List<String> userIdList = new ArrayList<>(Arrays.asList(split));

        if(userIdList.isEmpty()){
            return wfApproveUserConfigVo;
        }
        // 获取用户信息
        List<SysUser> sysUserList = userService.selectListByIds(userIdList);
        Map<String, SysUser> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, item -> item));

        // 给列表中的审批人名称赋值
        List<String> approveNodeUserNames = new ArrayList<>();
        for (String userId : split) {
            SysUser sysUser = sysUserMap.get(userId);
            if(sysUser != null) approveNodeUserNames.add(sysUser.getNickName());
        }
        wfApproveUserConfigVo.setApproveNodeUserNames(String.join(",", approveNodeUserNames));

        return wfApproveUserConfigVo;
    }

    /**
     * 查询流程审批人配置列表
     */
    @Override
    public TableDataInfo queryPageList(WfApproveUserConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WfApproveUserConfig> lqw = buildQueryWrapper(bo);
        Page<WfApproveUserConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<WfApproveUserConfigVo> records = result.getRecords();
        // 给列表中的审批人名称赋值
        handleApproveNodeUserName(records);

        return TableDataInfo.build(result);
    }

    private void handleApproveNodeUserName(List<WfApproveUserConfigVo> records) {
        // 获取列表中所有的审批人id
        List<String> userIdList = new ArrayList<>();
        records.forEach(item -> {
            String approveNodeUserIds = item.getApproveNodeUserIds();
            if (StringUtils.isNotEmpty(approveNodeUserIds)) {
                String[] split = approveNodeUserIds.split(",");
                userIdList.addAll(Arrays.asList(split));
            }
        });
        if(userIdList.isEmpty()){
            return;
        }
        // 获取用户信息
        List<SysUser> sysUserList = userService.selectListByIds(userIdList);
        Map<String, SysUser> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, item -> item));

        // 给列表中的审批人名称赋值
        records.forEach(item -> {
            String approveNodeUserIds = item.getApproveNodeUserIds();
            if (StringUtils.isNotEmpty(approveNodeUserIds)) {
                String[] split = approveNodeUserIds.split(",");
                List<String> approveNodeUserNames = new ArrayList<>();
                for (String userId : split) {
                    SysUser sysUser = sysUserMap.get(userId);
                    if(sysUser != null) approveNodeUserNames.add(sysUser.getNickName());
                }
                item.setApproveNodeUserNames(String.join(",", approveNodeUserNames));
            }
        });
    }

    /**
     * 查询流程审批人配置列表
     */
    @Override
    public List<WfApproveUserConfigVo> queryList(WfApproveUserConfigBo bo) {
        LambdaQueryWrapper<WfApproveUserConfig> lqw = buildQueryWrapper(bo);
        List<WfApproveUserConfigVo> list = baseMapper.selectVoList(lqw);
        // 给列表中的审批人名称赋值
        handleApproveNodeUserName(list);
        return list;
    }

    private LambdaQueryWrapper<WfApproveUserConfig> buildQueryWrapper(WfApproveUserConfigBo bo) {
        // 所属公司id
        String companyId = deptService.selectCompanyIdtByUserId(SecurityUtils.getLoginUser().getDeptId());

        LambdaQueryWrapper<WfApproveUserConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(WfApproveUserConfig::getDeptId, companyId);
        lqw.orderByDesc(BaseEntity::getCreateTime);
        return lqw;
    }

    /**
     * 新增流程审批人配置
     */
    @Override
    public WfApproveUserConfigVo insertByBo(WfApproveUserConfigBo bo) {
        WfApproveUserConfig add = ConvertUtils.sourceToTarget(bo, WfApproveUserConfig.class);
        add.setId(IdWorker.getId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return ConvertUtils.sourceToTarget(add, WfApproveUserConfigVo.class);
    }

    @Override
    public boolean initData() {
        List<WfApproveUserConfig> list = new ArrayList<>();
        // 所属公司id
        String companyId = deptService.selectCompanyIdtByUserId(SecurityUtils.getLoginUser().getDeptId());

        EnumSet<ApproveCodeConfigEnum> colorSet = EnumSet.allOf(ApproveCodeConfigEnum.class);
        for (ApproveCodeConfigEnum approveCodeConfig : colorSet) {
            WfApproveUserConfig wfApproveUserConfig = new WfApproveUserConfig();
            wfApproveUserConfig.setId(IdWorker.getId());
            wfApproveUserConfig.setDeptId(companyId);
            wfApproveUserConfig.setApproveCode(approveCodeConfig.getCode());
            wfApproveUserConfig.setApproveNodeName(approveCodeConfig.getDesc());
            list.add(wfApproveUserConfig);
        }

        return baseMapper.insertBatch(list);
    }

    /**
     * 修改流程审批人配置
     */
    @Override
    public WfApproveUserConfigVo updateByBo(WfApproveUserConfigBo bo) {
        WfApproveUserConfig update = ConvertUtils.sourceToTarget(bo, WfApproveUserConfig.class);
        baseMapper.updateById(update);
        return ConvertUtils.sourceToTarget(update, WfApproveUserConfigVo.class);
    }

    /**
     * 批量删除流程审批人配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteByIds(ids) > 0;
    }
}
